#!/usr/bin/python
# -*- coding: utf-8 -*-

import re,urllib2,sys

__all__ = ['down_pic']

class down_pic:
	html_file	=	'./aa.htm'
	tmp		=	None
	addr		=	list()
	img_src		=	str()
	support_type	=	('jpg','png','img','gif','bmp','swf')
	
	def  __init__ (self):
		self.tmp	=	re.findall("<[iI][mM][gG][^>]{1,}>",open(self.html_file,"rb").read())
	
	def get_pic_addr(self):
		self.addr	=	list()
		for i in self.tmp:
			self.img_src = re.findall("[sS][Rr][cC]=",i)[0]
			for j in i.split():
				if re.compile(self.img_src+"[\"']{0,1}http").match(j):
					if "'" in j:
						j=j.replace("'","")
					elif '"' in j:
						j=j.replace('"','')
					if ">" in j:
						j=j.replace(">","")
					j=j.replace(self.img_src,"")
					#self.addr.append(j)
					if j not in self.addr:
						self.addr.append(j)

	def download(self,download_list,download_type):
		num	=	0
		for i in download_list:
			pre_zeros	= '0'*(len(str(len(download_list)))-len(str(num)))
			#print len(str(len(download_list)))-len(str(num))
			try:
				open("./"+pre_zeros+str(num)+download_type,"wb").write( urllib2.urlopen(i).read())
				#open("./"+str(num)+download_type,"wb").write( urllib2.urlopen(i).read())
			except:
				pass
				sys.stderr.write("\n\tDownload "+i+" error!\n")
			finally:
				num	=	num+1
		
			
	def down_all(self):
		self.get_pic_addr()
		self.down_lst	=	self.addr
		self.download(self.down_lst,".img")

	def down_jpg(self):
		self.get_pic_addr()
		self.down_type	=	"jpg"
		self.down_lst	=	list()
		for i in self.addr:
			if re.compile(".*\."+self.down_type+"$").match(i.lower()):
				self.down_lst.append(i)
		self.download(self.down_lst,"."+self.down_type)
			
	def down_png(self):
		self.get_pic_addr()
		self.down_type	=	"png"
		self.down_lst	=	list()
		for i in self.addr:
			if re.compile(".*\."+self.down_type+"$").match(i.lower()):
				self.down_lst.append(i)
		self.download(self.down_lst,"."+self.down_type)

	def down_select_type(self,download_type):
		self.get_pic_addr()
		self.down_type	=	download_type
		self.down_lst	=	list()
		for i in self.addr:
			if re.compile(".*\."+self.down_type+"$").match(i.lower()):
				self.down_lst.append(i)
		self.download(self.down_lst,"."+self.down_type)

if __name__ == '__main__':
	Down	=	down_pic()
	if len(sys.argv) < 2:
		Down.down_jpg()
	elif sys.argv[1] in Down.support_type:
		Down.down_select_type( sys.argv[1] )
	elif sys.argv[1].lower() == 'all':
		Down.down_all()
	else:
		sys.stderr.write("\n\tUnknown type!\n")
		



